/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package ui.helpers;

import core.Database;
import core.DatabaseTable;

import ui.ApplicationWindow;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JOptionPane;
import org.apache.log4j.Logger;

/**
 *
 * @author Sakis Vtdk <sakis.vtdk@gmail.com>
 */
public class NewTableListener implements ActionListener
{
	@Override
	public void actionPerformed(ActionEvent evt)
	{
		String tableName = null;
		boolean accepted;
		do
		{
			//create a dialog to get the name of the new table
			accepted = true;
			String tblName = JOptionPane.showInputDialog(null, "Enter name for the new table", "New Table", JOptionPane.PLAIN_MESSAGE);
			if(tblName != null)
			{
				try
				{
					Database.getDatabase().addTable(new DatabaseTable(tblName));
					tableName = tblName;
				}
				catch(IllegalArgumentException e)
				{
					JOptionPane.showMessageDialog(null, "Could not create table "+ tblName +"'. Try another.", "Error" , JOptionPane.ERROR_MESSAGE);
					log.warn("Unable to create table '"+ tblName +"'. The error returned was: "+ e.getMessage());
					accepted = false;       
				}
				catch(Exception e)
				{
					JOptionPane.showMessageDialog(null, "There is already a table '"+ tblName +"'. Try another.", "Error" , JOptionPane.ERROR_MESSAGE);
					log.warn("Unable to create table. There is already a table named '"+ tblName +"'. The error returned was: "+ e.getMessage());
					accepted = false;
				}       
			}
			
		}while(!accepted);

		ApplicationWindow.getApplicationWindow().refreshItems();

		ApplicationWindow.getApplicationWindow().selectItemInJtree(tableName);
	}


	private final String NEW_TABLE_COMMAND = "Create new table...";

	private static Logger log = Logger.getLogger(NewTableListener.class);
}
